package domain

import (
	"context"

	"github.com/lab-online/internal/report/constant"
	"github.com/lab-online/internal/report/entity"
	"github.com/lab-online/internal/shared/code"
	"github.com/lab-online/pkg/auth"
)

func (d *Domain) SubscribeReport(
	ctx context.Context,
	authEntity auth.AuthEntity,
	report entity.ReportEntity,
	body chan<- []byte,
) error {
	if savedReport, err := d.repository.GetReportByID(report.GetID()); err != nil {
		return code.ErrorPicker(
			err, code.DatabaseReportNotFound, constant.RESTErrReportNotFound,
		)
	} else if !(authEntity.IsSelf(savedReport.GetStudent()) || authEntity.IsEnabled(auth.RoleAdmin)) {
		return constant.RESTErrNoPermissionToGet
	} else if savedReport.GetStatus() <= code.StatusSolid {
		select {
		case <-ctx.Done():
		case body <- []byte(savedReport.GetContent()):
		}
		return nil
	}

	return d.mq.SubscribeReport(ctx, report.GetID(), body)
}
